from flask import Blueprint, request, jsonify
from .compan import get_data
from utils.db import db1
import json
import datetime

bp_book = Blueprint('books', __name__)


# 登录
@bp_book.route('/zlogin', methods=['POST', 'GET'])
def zlogin():
    if request.method == 'POST':
        try:
            data = get_data()
            sql = """select * from zuser where username = '%s'""" % (data['username'])
            res = db1.findone(sql)
            if res['username']:
                if res['password'] == data['password']:
                    return jsonify({'code': 200, "mes": "登陆成功", "userid": res['id']})
                else:
                    return jsonify({'code': 10010, "mes": "密码错误"})
            else:
                return jsonify({'code': 10011, "mes": "账号不存在"})
        except:
            return jsonify({'code': 10011, "mes": "网络出错了"})

# 无限极
def xtree(data):
    list = []
    dict = {}
    if data:
        for j in data:
            dict[j['id']] = j

        for i in data:
            if i['pid'] == 0:
                list.append(i)
            else:
                if 'son' not in dict[i['pid']]:
                    dict[i['pid']]['son'] = []
                dict[i['pid']]['son'].append(i)
        return list


@bp_book.route('/get_zy')
def get_zy():
    userid = request.args.get('userid')
    sql = """select res.id,res.url,res.name,res.pid from resources as res inner join users_resource as us on res.id = us.resid where userid=%d""" % int(
        userid)
    res = db1.findall(sql)
    list = xtree(res)
    return jsonify({'code': 200, "list": list})


# 发布文章
@bp_book.route('/add_book', methods=['GET', 'POST'])
def add_book():
    if request.method == 'POST':
        data = get_data()
        userid = request.args.get('userid')
        date = datetime.datetime.now()
        nowtime = date.strftime("%Y-%m-%d %H:%M:%S")
        sql = """insert into books(title,content,userid,status,stime) values('%s','%s',%d,%d,'%s')""" % (
        data['title'], data['content'], int(userid), 1, nowtime)
        db1.update(sql)
        return jsonify({'code': 200})


# 获取我的文章

@bp_book.route('/get_wz')
def get_wz():
    userid = request.args.get('userid')
    if userid:
        sql = """select * from books where userid = %d""" % int(userid)
        res = db1.findall(sql)
        return jsonify({'code': 200, "list": res})
    else:
        sql = """select * from books where status = 1"""
        res = db1.findall(sql)
        return jsonify({'code': 200, "list": res})
#通过
@bp_book.route('/agreen')
def agreen():
    id = request.args.get('id')
    sql = """update books set status=2 where id = %d"""%int(id)
    db1.update(sql)
    sql3 = """select * from books where id = %d"""%int(id)
    res = db1.findone(sql3)
    sql2 = """select * from zuser where id = %d"""%int(res['userid'])
    ress = db1.findone(sql2)
    jf = int(ress['jifen']) + 2
    sql1 = """update zuser set  jifen = %d where id = %d"""%(jf,int(res['userid']))
    db1.update(sql1)

    # sql4 = """select * from echarss where userid = %d"""%int(res['userid'])
    # aa = db1.findall(sql4)
    # if aa:
    #     for i in aa:
    #         date = datetime.datetime.now()
    #         nowtime = date.strftime("%Y-%m-%d 00:00:00")
    #         if i['times'] == nowtime:
    #             sql6 = """select * from echarss where userid = %d and times = '%s'"""%(int(res['useri']),nowtime)
    #             fenn = db1.findone(sql6)
    #             numm = int(fenn['fen']) + 2
    #             sql5 = """update echarss set fen = %d where userid = %d"""%(numm,int(res['userid']))
    #             db1.update(sql5)
    # else:
    #     date = datetime.datetime.now()
    #     nowtime = date.strftime("%Y-%m-%d")
    #     sql7 = """insert into echarss(times,fen,userid) values('%s',%d,%d)"""%(nowtime,2,int(res['userid']))
    #     db1.update(sql7)
    return jsonify({"code":200})
#不通过
@bp_book.route('/noagreen')
def noagreen():
    id = request.args.get('id')
    sql = """update books set status=3 where id = %d""" % int(id)
    db1.update(sql)
    return jsonify({"code": 200})

#添加奖品
@bp_book.route('/add_jift',methods = ['POST','GET'])
def add_jift():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into jift(name,price,kc,needjf) values('%s',%d,%d,%d)"""%(data['name'],int(data['price']),int(data['kc']),int(data['needjf']))
        db1.update(sql)
        return jsonify({'code':200})

#获取奖品
@bp_book.route('/giftM')
def giftM():
    sql = """select * from jift"""
    res = db1.findall(sql)
    return jsonify({'code':200,"list":res})

#获取用户积分
@bp_book.route('/jfM')
def jfM():
    userid = request.args.get('userid')
    sql = """select * from zuser where id = %d"""%int(userid)
    res = db1.findone(sql)
    return jsonify({'code':200,"numm":res['jifen']})

#兑换奖品
@bp_book.route('/dhM',methods=['GET', 'POST'])
def dhM():
    if request.method == 'POST':
        data = get_data()
        sql = """select * from jift where id = %d"""%int(data['id'])
        res = db1.findone(sql)
        if int(res['needjf']) > int(data['jf']):
            return jsonify({'code':20010,"mes":'不好意思，您的积分不足以兑换此商品'})
        else:
            sql1 = """insert into gift_user(userid,giftid) values(%d,%d)"""%(int(data['userid']),int(data['id']))
            db1.update(sql1)
            sql2 = """select * from jift where id = %d"""%int(data['id'])
            qq = db1.findone(sql2)
            kc = int(qq['kc']) - 1
            sql3 = """update jift set kc = %d where id = %d"""%(kc,int(data['id']))
            db1.update(sql3)
            sql4 = """select * from zuser where id = %d"""%(int(data['userid']))
            ress = db1.findone(sql4)
            jf = int(ress['jifen']) - int(qq['needjf'])
            sql5 = """update zuser set jifen = %d where id = %d"""%(jf,int(data['userid']))
            db1.update(sql5)
            return jsonify({'code':200,"mes":"兑换成功"})

#echars
@bp_book.route('/echars')
def echars():
    userid = 2
    # sql = """select * from zuser where id = %d"""%int(userid)
    # res = db1.findone(sql)
    sql1 = """select stime from books where userid = %d"""%int(userid)
    ress = db1.findall(sql1)
    print(ress)
    list = []
    for i in ress:
        list.append(i['stime'])
    return jsonify({'code':200,"datess":list})



















